package com.lzqinga.util;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * - @author lzqinga
 * - @description
 * - @date 2025/10/10/010 12:56
 **/
@Slf4j
public class FileUtil {

    public static void ensureDirectoryExists(String directoryPath) throws IOException {
        Path path = Paths.get(directoryPath);
        if (!Files.exists(path)) {
            Files.createDirectories(path);
            log.info("创建目录: {}", directoryPath);
        }
    }
    public static void saveBinaryData(byte[] data, String outputPath) throws IOException {
        ensureDirectoryExists(Paths.get(outputPath).getParent().toString());

        try (FileOutputStream fos = new FileOutputStream(outputPath)) {
            fos.write(data);
        }
        log.info("文件保存到: {}", outputPath);
    }

    /**
     * 获取项目根目录的 data 文件夹路径
     */
    public static String getDataFolderPath(String child) {
        try {
            // 方法1: 通过当前工作目录
            File currentDir = new File("");
            String projectRoot = currentDir.getCanonicalPath();
            File dataDir = new File(projectRoot, child);

            if (!dataDir.exists()) {
                dataDir.mkdirs();
                System.out.println("创建 data 目录: " + dataDir.getAbsolutePath());
            }

            return dataDir.getAbsolutePath();

        } catch (IOException e) {
            throw new RuntimeException("获取 data 目录失败", e);
        }
    }

    /**
     * 获取 data 文件夹下的文件绝对路径
     */
    public static String getDataFilePath(String fileName, String child) {
        File dataFile = new File(getDataFolderPath(child), fileName);
        return dataFile.getAbsolutePath();
    }

    /**
     * 获取 data 文件夹下的所有文件
     */
    public static List<String> getDataFiles() {
        File dataDir = new File(getDataFolderPath("data"));
        if (!dataDir.exists() || !dataDir.isDirectory()) {
            return new ArrayList<>();
        }

        return Arrays.stream(dataDir.listFiles())
                .map(File::getAbsolutePath)
                .collect(Collectors.toList());
    }
}
